import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { Component, OnInit, ViewChild, ElementRef, OnDestroy, NgZone, Type } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { IonContent, AlertController, ModalController } from '@ionic/angular';

import { ActionSheetService, Modal } from 'ng-zorro-antd-mobile';

import { OpenAppComponent } from '../coms/open-app/open-app.component';
import { PopoverController } from '@ionic/angular';
import { SharePageComponent } from '../coms/share-page/share-page.component';
import { ComItem } from '../route/entry/com-item';
import { AppGlobalService } from '../shared/service/app-global.service';
import { EventService } from '../shared/service/event.service';
import { HttpService } from '../shared/service/http.service';
import { MapBaiduService } from '../shared/service/map.baiduapi';
import { TabsService } from '../shared/service/tabs.service';
import { PopoverComponent } from '../coms/popover/popover.component';
declare var $: any;
@Component({
  selector: 'app-details',
  templateUrl: '../route/entry/entry.page.html',
  styleUrls: ['../route/entry/entry.page.scss'],
})
export class DetailsComponent implements OnInit, OnDestroy {

  isLoading = false;
  headerComs: ComItem[];
  menusBar: any;
  coms: ComItem[];
  subComs: ComItem[];
  footerComs: ComItem[];
  sessionId: string;
  params: any = '';
  viewId: any;
  // 标签头数据
  titleBar: any;
  isHeader = true;
  isGrayBg = false; // 默认背景为灰色
  bgCssStyle = ''; // 默认背景为灰色
  isPageDisabled = false;
  backgroundImg: string; // 头部背景图片
  showWaterImg = false;
  showRefresher = false; // 下拉刷新
  showLoading = false;
  showEmptyMessage = false;

  // 位置对象
  positionInfo: any = {};
  // 小区位置信息
  areaPositionInfo: any = {};
  showTopTab = false; // 是否显示顶部tab
  showSubTab = false; // 是否显示Subtab
  subTagData: any; // 顶部tab data
  subAWidth: string;
  tagData: any;
  aWidth: string;
  pageParams: any;
  isFirst = true;
  openBackdrop: boolean;
  showRefresh = false; // 是否显示刷新
  netState: any; // 网络状态
  isScrolling = false;
  private timer: any;
  // 路由对象
  routerSub: any;
  pageId;
  // 分享页面数据
  shareData = {
    icon: "share.png",
    layout: "right",
    submit: {
      content: {},
      id: "string"
    }
  };
  keyword: any;
  @ViewChild('superCotainer') scrollContent: ElementRef;
  @ViewChild(IonContent) content: IonContent;
  showScrollToTopBtn = false; // 是否显示滑动到顶部按钮
  isAddCommonNestedTag = true;
  serviceLink: any;
  showDivTips = false;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    public alertController: AlertController,
    public appGlobalService: AppGlobalService,
    private modalController: ModalController,
    private eventService: EventService,
    private mapBaiduService: MapBaiduService,
    private pageModalService: PageModalService,
    private ngZone: NgZone,
    private http: HttpService,
    private tabs: TabsService,
    public popoverController: PopoverController
  ) { }

  ngOnInit() {
    // debug 分享的小程序商品直接下单 微信登录code没有及时与sessionId 绑定bug
    if (this.eventService.eventEmit.listenerCount("bindWeChatLoginCode") > 0) {
      this.eventService.eventEmit.removeListener("bindWeChatLoginCode");
    }
    this.eventService.eventEmit.on("bindWeChatLoginCode", (data) => {
      // 与微信绑定
      if (this.appGlobalService.wxLoginCode) {
        this.http.bindWeChatLoginCode(success => {
          if (localStorage.getItem('loginAccount') === "19168928480") {
            alert('wxlogincode bind:' + success);
          }
        });
      }
    });
    //
    localStorage.removeItem('detailsParams');
    localStorage.removeItem('details?id');

    if (this.eventService.eventEmit.listenerCount('refreshPageData' + localStorage.getItem('currentPath')) > 0) {
      this.eventService.eventEmit.removeListener('refreshPageData' + localStorage.getItem('currentPath'));
    }
    this.eventService.eventEmit.on('refreshPageData' + localStorage.getItem('currentPath'), pageData => {
      console.log(' h5 刷新页面 ------->\n');
      // 2024.05.11 刷新前对数据做检查
      if (pageData.coms && pageData.coms.length > 0) {
        this.coms = pageData.coms;
      }
      if (pageData.headerComs && pageData.headerComs.length > 0) {
        this.headerComs = pageData.headerComs;
      }
      if (pageData.subComs && pageData.subComs.length > 0) {
        this.subComs = pageData.subComs;
      }
      if (pageData.titleBar) {
        this.titleBar = pageData.titleBar;
      }
      if (pageData.footerComs && pageData.footerComs.length > 0) {
        this.footerComs = pageData.footerComs;
      }
      if (pageData.isGrayBg) {
        this.isGrayBg = pageData.isGrayBg;
      }
      if (pageData.bgCssStyle) {
        this.bgCssStyle = pageData.bgCssStyle;
      }
      if (pageData.disabled) {
        this.isPageDisabled = pageData.disabled;
      }
      if (pageData.showRefresher) {
        this.showRefresher = pageData.showRefresher;
      }
      if (pageData.showLoading) {
        this.showLoading = pageData.showLoading;
      }
      if (pageData.backgroundImg) {
        this.backgroundImg = pageData.backgroundImg;
      }
      if (pageData.showWaterImg) {
        this.showWaterImg = pageData.showWaterImg;
      }
      // this.getCurrentToggleData();
    });



    this.openBackdrop = this.appGlobalService.openBackdrop;


    // 订阅路由
    this.routerSub = this.router.events.subscribe((event: NavigationEnd) => {
      if (event instanceof NavigationEnd) {

        // 判断是否有参数
        if (this.route.queryParams) {
          // 路由取值
          this.route.queryParams.subscribe(queryParams => {
            // 2024.02.29 标识访问类型为H5
            localStorage.setItem('detailPageFromH5', 'true');
            localStorage.setItem('appVersion', this.appGlobalService.appVersion);
            if (queryParams.params !== undefined) {
              if (new Date().getTime() - this.appGlobalService.lastPageTime < 2000) {
                console.log('NO need  queryParams.params  again~');
                return;
              }
              this.appGlobalService.lastPageTime = new Date().getTime();
            }
            console.log('参数：', queryParams.params);

            // if (localStorage.getItem('detailsParams') === queryParams.params) {
            //   return;
            // } else {
            //   localStorage.setItem('detailsParams', queryParams.params);
            //   setTimeout(() => {
            //     localStorage.removeItem('detailsParams');
            //   }, 5000);
            // }

            if (queryParams.code && queryParams.state) {

              // 微信浏览器支付
              this.appGlobalService.wxPayCode = queryParams.code;
              // if (localStorage.getItem('loginAccount') === "19168928480") {
              //     alert('details wx code :' + this.appGlobalService.wxPayCode);
              // }
              let pageParams = queryParams.state;
              if (pageParams.indexOf('%') > -1) {
                pageParams = decodeURIComponent(pageParams);
              }
              // alert('pageParams:' + JSON.stringify(pageParams) );
              pageParams = JSON.parse(pageParams);
              pageParams.params['replace'] = 'replace';
              pageParams.params['h5flag'] = "1"; // 为了支付完成展示弹窗
              // this.router.navigate([pageParams.params.currentPath], { queryParams: pageParams });

              // this.appGlobalService.popTarget();
              // if (localStorage.getItem('loginAccount') === "19168928480") {
              //     alert('details page Params:' + JSON.stringify(pageParams) );
              //   }

              this.getPage(pageParams);
            } else if (queryParams.successParams) {

              // 小程序支付成功
              // alert('支付成功!');
              const pageParams = JSON.parse(queryParams.successParams);
              this.getPage(pageParams);

            } else if (queryParams.failParams) {
              const pageParams = JSON.parse(queryParams.failParams);
              // alert('支付失败!');
              this.getPage(pageParams);
            }

            // 存在参数
            if (queryParams.params) {
              if (queryParams.params.indexOf('%') > -1) {
                let temp: any;
                temp = decodeURIComponent(queryParams.params);
                if (temp.indexOf('%') > -1) {
                  temp = decodeURIComponent(temp);
                  if (temp.indexOf('%') > -1) {
                    temp = decodeURIComponent(temp);
                    if (temp.indexOf('%') > -1) {
                      temp = decodeURIComponent(temp);
                    } else {
                      this.params = temp;
                    }
                  } else {
                    this.params = temp;
                  }
                } else {
                  this.params = temp;
                }
                if (typeof (this.params) === 'string') {
                  this.params = JSON.parse(this.params);
                }

              } else {
                this.params = JSON.parse(queryParams.params);
              }

              // 2.2.2 新增用于submit标识分享
              if (this.params.fromH5forRecord !== undefined
                && this.params.fromH5forRecord === 'true'
                && this.params.base_info_id !== undefined) {
                this.appGlobalService.fromH5forRecord = this.params.base_info_id;
              }

              // 2.0 新增
              if (this.params.isView !== undefined && this.params.isView === 'true') {
                localStorage.setItem('ShareH5', JSON.stringify(this.params));
                const path = 'home/tab1';
                this.router.navigate([path], { queryParams: { paramsStr: JSON.stringify(this.params) } });
                return;
              }
              if (queryParams.wxLoginCode) {
                // wx send loginCode
                // alert('扫码 wxLoginCode' + queryParams.wxLoginCode);
                this.appGlobalService.wxLoginCode = queryParams.wxLoginCode;
                if (this.appGlobalService.getSessionPath === undefined) {
                  this.appGlobalService.getSessionPath = "application/openApp/xw/" + this.appGlobalService.ReleaseVersionCode;
                }
                localStorage.removeItem('sessionId'); // 请求新session 先删除旧session
                this.http.get(this.appGlobalService.getSessionPath, res => {
                  localStorage.setItem('sessionId', res.sessionId);
                  setTimeout(() => {
                    const params = {
                      session: res.sessionId, // localStorage.getItem('sessionId'),
                      type: this.params.type || 'opp',
                      plugin_id: this.params.plugin_id
                    };
                    console.log('queryParams.sessionId -> getPageId --this.params:' + JSON.stringify(this.params));
                    this.getPageId(params);
                  }, 100);
                });
                // 小程序定位信息
                let wxLat = this.appGlobalService.defaultCityCenter.lat;
                if (queryParams.lat) {
                  wxLat = queryParams.lat;
                }
                let wxLng = this.appGlobalService.defaultCityCenter.lng;
                if (queryParams.lng) {
                  wxLng = queryParams.lng;
                }
                const position = {
                  name: this.appGlobalService.defaultCityName,
                  code: this.appGlobalService.defaultCityId,
                  center: { lng: wxLng, lat: wxLat }
                };
                localStorage.setItem('locationFromWx', JSON.stringify(position));

              } else if (this.params.pageId) {
                // 20231013 H5 sessionId重新请求导致无法立即购买
                if (localStorage.getItem("sessionId") && localStorage.getItem("sessionId") !== 'null') {
                  const param = {
                    pageId: this.params.pageId,
                    params: this.params, // update by andrew.wen for  案例分享，合同id参数没传过去，导致打开分享链接是空白页
                    sessionId: localStorage.getItem("sessionId")  // localStorage.getItem('sessionId')
                  };
                  console.log('queryParams.wxLoginCode -> getPageId --this.params:' + JSON.stringify(this.params));
                  this.getPage(param);
                } else {
                  let url = 'application/openApp/xw/' + this.appGlobalService.ReleaseVersionCode;
                  // console.log('href=' , window.location.href);
                  if (window.location.href.indexOf('m-fengwo168.xwkj.local') !== -1 || window.location.href.indexOf('localhost') !== -1) {
                    url = 'application/debug/' + this.appGlobalService.debugAppId;
                  } else {
                    // 存在sessionId为空的情况
                    if (this.appGlobalService.getSessionPath) {
                      url = this.appGlobalService.getSessionPath;
                    }
                  }
                  if (localStorage.getItem('reGetSession') === 'true') {
                    const param = {
                      pageId: this.params.pageId,
                      params: this.params,
                      sessionId: localStorage.getItem('sessionId')
                    };
                    this.getPage(param);

                  } else {
                    localStorage.removeItem('sessionId'); // 请求新session 先删除旧session
                    this.http.get(url, res => {
                      localStorage.setItem("sessionId", res.sessionId);
                      localStorage.setItem("reGetSession", "true");
                      setTimeout(() => {
                        localStorage.removeItem("reGetSession");
                      }, 5000);
                      const param = {
                        pageId: this.params.pageId,
                        params: this.params,
                        sessionId: res.sessionId
                      };
                      this.getPage(param);
                    });
                  }

                }

              } else
                if (queryParams.sessionId) {
                  // wx send sessionId
                  // alert('扫码 sessionId' + queryParams.sessionId);
                  localStorage.setItem('sessionId', queryParams.sessionId);
                  setTimeout(() => {
                    const params = {
                      session: localStorage.getItem('sessionId'),
                      type: this.params.type || 'opp',
                      plugin_id: this.params.plugin_id
                    };
                    this.getPageId(params);
                  }, 100);
                } else {
                  console.log('msg----->details' + new Date().getMilliseconds());
                  console.log('href=', window.location.href);
                  if (this.pageId) {
                    return;
                  }
                  if (localStorage.getItem("isFromShareH5Page2")) {
                    return;
                  }
                  let url = 'application/openApp/xw/' + this.appGlobalService.ReleaseVersionCode;
                  // console.log('href=' , window.location.href);
                  if (window.location.href.indexOf('m-fengwo168.xwkj.local') !== -1 || window.location.href.indexOf('localhost') !== -1) {
                    url = 'application/debug/' + this.appGlobalService.debugAppId;
                  } else {
                    // 存在sessionId为空的情况
                    if (this.appGlobalService.getSessionPath) {
                      url = this.appGlobalService.getSessionPath;
                    }
                  }

                  if (localStorage.getItem('reGetSession') === 'true') {
                    const params = {
                      session: localStorage.getItem('sessionId'),
                      type: this.params.type || 'opp',
                      plugin_id: this.params.plugin_id
                    };
                    console.log('after get sessionId -> getPageId --this.params:' + JSON.stringify(this.params));
                    this.getPageId(params);

                  } else {
                    localStorage.removeItem('sessionId'); // 请求新session 先删除旧session
                    this.http.get(url, res => {
                      localStorage.setItem("sessionId", res.sessionId);
                      localStorage.setItem("reGetSession", "true");
                      setTimeout(() => {
                        localStorage.removeItem("reGetSession");
                      }, 5000);
                      const params = {
                        session: localStorage.getItem('sessionId'),
                        type: this.params.type || 'opp',
                        plugin_id: this.params.plugin_id
                      };
                      console.log('after get sessionId -> getPageId --this.params:' + JSON.stringify(this.params));
                      this.getPageId(params);
                    });
                  }
                }
            }

            // 短链分享 http://m-fengwo168.xwkj.local/#/details?id=7e21e114-0f05-4ff3-b61d-60bbbb1149474

            if (queryParams.id && queryParams.id.length > 0) {
              // if (localStorage.getItem('details?id') === queryParams.id) {
              //   return;
              // } else {
              //   localStorage.setItem('details?id', queryParams.id);
              //   setTimeout(() => {
              //     localStorage.removeItem('details?id');
              //   }, 5000);
              // }
              if (new Date().getTime() - this.appGlobalService.lastTime < 2000) {
                console.log('NO need getShareUrlByShortUrl again~');
                return;
              }
              this.appGlobalService.lastTime = new Date().getTime();
              this.http.get('element/getShareUrlByShortUrl/' + queryParams.id, res => {
                console.log(res);
                console.log(res.url);
                if (res.url && res.url.length > 1) {
                  let url = res.url;


                  if (res.url.indexOf('/home/tab1/details') > -1) {
                    url = res.url.replace('home/tab1/', '');
                  }
                  // 避免与扫码小程序冲突
                  if (res.url.indexOf('/home/tab2/details') > -1) {
                    url = res.url.replace('home/tab2/', '');
                  }

                  // 本地调试用
                  // if (url.indexOf('https://m.fengwo168.com') > -1) {
                  //   url = url.replace('https://m.fengwo168.com', 'http://localhost:8100');
                  // }
                  // 第一次进来判断有没有sessionId
                  // let sessionId = '';

                  // // 如果有则传递到详情页面用来登录和立即购买 确定始终用的是同一个sessionId
                  // if (localStorage.getItem('sessionId') && localStorage.getItem('sessionId') !== 'null') {
                  //   sessionId = localStorage.getItem("sessionId");
                  //   url = url + '&sessionId=' + sessionId;
                  // }
                  console.log('短链换成长链接:' + url);
                  // window.location.replace(url);
                  const path = '/details';
                  localStorage.removeItem("targetObj");
                  this.router.navigate([path], { queryParams: { params: url.split('=')[1] } });
                } else {
                  this.appGlobalService.showToast('链接已失效', 1500, 'top');
                }
              });
            }
            // 如果是画报分享 则显示引导按钮。 并且是app端
            if (queryParams.posterSharing) {
              // if (localStorage.getItem('client') && localStorage.getItem('client') !== 'APP') {
              console.log('msg-----> posterSharing...');
              try {
                const en = window.navigator.userAgent.toLowerCase();
                const isWeixin = en.indexOf('micromessenger') !== -1;
                if (!isWeixin) {
                  this.openPpwAppModal("open-ppw-app");
                  // window.location.href = 'xiaowang://';
                }
              } catch (error) {

              }
            }
            // }
          });
        }
      }
    });
  }


  async openPpwAppModal(className) {
    try {
      const modal = await this.modalController.create({
        showBackdrop: false,
        backdropDismiss: false,
        cssClass: className,
        animated: true,
        component: OpenAppComponent,
        componentProps: {}
      });
      await modal.present();
      // 监听销毁的事件
      const modalData = await modal.onDidDismiss(); // 获取关闭传回的值

    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }

  }

  // 分享弹框
  async presentModal() {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: this.shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }
  /** 分享 */
  share(link) {
    if (link && link.params
      && link.params.doNotRequestPageBeforeJumpToSharePage !== undefined
      && link.params.doNotRequestPageBeforeJumpToSharePage === 'true') {
      this.pageModalService.openPage(link);
    } else {
      // 请求参数
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: link.target,
        params: link.params
      };
      this.http.post('application/page', params, res => {
        console.log(JSON.parse(res.script));
        this.shareData = JSON.parse(res.script).views[0].tags[0].data;
        console.log(this.shareData);
        this.presentModal();
      });
    }
  }

  // 获取页面ID
  getPageId(params) {
    if (this.params && this.params.pageId) {
      this.pageId = this.params.pageId;
      const param = {
        pageId: this.params.pageId,
        params: this.params,
        sessionId: localStorage.getItem('sessionId')
      };
      this.getPage(param);
    } else {
      this.http.post('element/pageId/getBySession', params, res => {
        localStorage.removeItem("tab1");
        console.log('ready to get page for page id =' + res.page + 's1=' + localStorage.getItem('sessionId') + '|s2=' + params.session);
        if (res && res.page) {
          this.pageId = res.page;
          const param = {
            pageId: res.page,
            params: this.params, // update by andrew.wen for  案例分享，合同id参数没传过去，导致打开分享链接是空白页
            sessionId: params.session  // localStorage.getItem('sessionId')
          };
          this.getPage(param);
        }

      }, (error) => {
        if (error && error.code == '5502') {
          let url = 'application/openApp/xw/' + this.appGlobalService.ReleaseVersionCode;
          if (window.location.href.indexOf('m-fengwo168.xwkj.local') !== -1 || window.location.href.indexOf('localhost') !== -1) {
            url = 'application/debug/' + this.appGlobalService.debugAppId;
          }
          if (localStorage.getItem("reGetSession") === "true") {
            params.sessionId = localStorage.getItem('sessionId');
            this.getPageId(params);
          } else {
            localStorage.removeItem('sessionId'); // 请求新session 先删除旧session
            this.http.get(url, res => {
              localStorage.setItem("reGetSession", "true");
              setTimeout(() => {
                localStorage.removeItem("reGetSession");
              }, 5000);
              localStorage.setItem('sessionId', res.sessionId);
              console.log('5502 -> getPageId');
              params.sessionId = localStorage.getItem('sessionId');
              this.getPageId(params);
            });
          }

        }
      });
    }
  }
  //  获取详情页面
  getPage(params) {
    const that = this;
    if (localStorage.getItem('position') !== null) {
      const postionInfo = JSON.parse(localStorage.getItem('position'));
      // tslint:disable-next-line:no-string-literal
      params.params['latitude'] = postionInfo.center.lat;
      // tslint:disable-next-line:no-string-literal
      params.params['longitude'] = postionInfo.center.lng;
    } else {
      // tslint:disable-next-line:no-string-literal
      params.params['latitude'] = this.mapBaiduService.locationObj.center.lat;
      // tslint:disable-next-line:no-string-literal
      params.params['longitude'] = this.mapBaiduService.locationObj.center.lng;
    }
    that.pageParams = params;
    // 用于session过期后，自动新session刷新page。如果请求过page,可以刷新当前page
    if (this.eventService.eventEmit.listenerCount("reGetDetailsPage") > 0) {
      this.eventService.eventEmit.removeListener("reGetDetailsPage");
    }
    this.eventService.eventEmit.on("reGetDetailsPage", (data) => {
      that.pageParams.sessionId = localStorage.getItem('sessionId');
      that.getPage(that.pageParams);
    });
    // 返回不重新请求page 如果是刚请求的新sessionid则允许刷新
    if (localStorage.getItem("reGetSession") !== "true" &&
      params.params.onlyBack && params.params.onlyBack === 'true' && this.coms && this.coms.length > 0) {
      return;
    }
    this.http.post('application/page', params, res => {
      console.log("details getProjectId");
      if (this.http.bathUrl.indexOf('https') > -1) {
        this.getProjectId();
      }
      this.tabs.getPageData(res, async pageData => {
        // 回到 主tab
        const pageDataTemp = JSON.parse(res.script);
        if (pageDataTemp.style === 'page.FramePageLogic') {
          // 清除访问历史
          this.appGlobalService.popAllTarget();
          setTimeout(() => {
            localStorage.setItem("needRefreshTab1", "true");
            localStorage.setItem("needRefreshTab2", "true");
            localStorage.setItem("needRefreshTab3", "true");
            localStorage.setItem("needRefreshTab4", "true");
            localStorage.setItem("needRefreshTab5", "true");
            this.router.navigate(['/home/tab1'], { queryParams: {}, replaceUrl: true });
          }, 100);

        }
        // console.log(pageData);
        this.coms = pageData.coms;
        // 如果是h5自定义分享过来的 单独处理
        this.handleH5CustomShare(params, this.coms);

        this.headerComs = pageData.headerComs;
        this.subComs = pageData.subComs;
        this.titleBar = pageData.titleBar;
        this.footerComs = pageData.footerComs;
        this.isGrayBg = pageData.isGrayBg;
        this.bgCssStyle = pageData.bgCssStyle;
        this.isPageDisabled = pageData.disabled;
        this.showRefresher = pageData.showRefresher;
        this.showLoading = pageData.showLoading;
        this.backgroundImg = pageData.backgroundImg;
        this.showWaterImg = pageData.showWaterImg;
        const ionScroll = this.content.getScrollElement();
        (await ionScroll).style.background = this.bgCssStyle;
      });
    }, (error) => {
      // httpservice 中已经自动请求sessionid 下面代码不用

      // if (error && error.code == '5502') {
      //   let url = 'application/openApp/xw/' + this.appGlobalService.ReleaseVersionCode;
      //   if (window.location.href.indexOf('m-fengwo168.xwkj.local') !== -1 || window.location.href.indexOf('localhost') !== -1) {
      //     url = 'application/debug/' + this.appGlobalService.debugAppId;
      //   }
      //   if (localStorage.getItem("reGetSession") === "true") {
      //     params.sessionId = localStorage.getItem('sessionId');
      //     this.getPage(params);
      //   } else {
      //     localStorage.removeItem('sessionId'); // 请求新session 先删除旧session
      //     this.http.get(url, res => {
      //       localStorage.setItem("reGetSession", "true");
      //       setTimeout(() => {
      //         localStorage.removeItem("reGetSession");
      //       }, 5000);
      //       localStorage.setItem('sessionId', res.sessionId);
      //       console.log('5502 -> re getPage', res.sessionId);
      //       params.sessionId = res.sessionId;
      //       this.getPage(params);
      //     });
      //   }

      // }
    });

    if (this.appGlobalService.wxLoginCode) {
      this.http.bindWeChatLoginCode((sessionId) => {
      });
    }
  }
  getProjectId() {
    this.http.get(
      "application/getProjectId/xw/" + this.appGlobalService.ReleaseVersionCode,
      (res) => {
        if (res.projectId) {
          localStorage.setItem("projectId", res.projectId);
        }
      });
  }
  handleH5CustomShare(data, comsArray) {
    // if (this.userAgent.match(/micromessenger/i) !== null) {
    if (data.params && comsArray) {
      if (data.params.type === 'lj_opp') {
        const array = comsArray;
        // tslint:disable-next-line:prefer-for-of
        for (let index = 0; index < array.length; index++) {
          const element = array[index];
          if (element.tagData
            && element.tagData.style === 'tag.AppSimpleDetailTagLogic'
            && element.tagData.data.cssType === '31-windowSetProperty') {
            if (element.tagData.data.title) {
              localStorage.setItem('indexTitle', element.tagData.data.title);
              console.log('indexTitle', element.tagData.data.title);
            }
            if (element.tagData.data.description) {
              localStorage.setItem('indexDesc', element.tagData.data.description);
              console.log('indexDesc', element.tagData.data.description);
            }
            if (element.tagData.data.imgUrl) {
              localStorage.setItem('indexImgUrl', element.tagData.data.imgUrl);
              console.log('indexImgUrl', element.tagData.data.imgUrl);
            }
            if (element.tagData.data.currentLink) {
              localStorage.setItem('currentLink', element.tagData.data.currentLink);
              console.log('currentLink', element.tagData.data.currentLink);
            }
            break;
          }
        }
      }
    }
    // }


  }

  scrollEnd(e: any) {
    this.isScrolling = false;
    e.preventDefault();
    // console.log('scrollEnd----->detail' );
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      // console.log('scrollEnd----->detail setTimeout' );
      if (this.appGlobalService.topTop) {
        this.appGlobalService.topTop = false;
        this.content.scrollToTop(200);
      }
    }, 300);
  }
  onScroll(e: any, titleBar?) {
    this.isScrolling = true;
    e.preventDefault();
    if (titleBar && titleBar.onScroll === 'false') {
      // 不处理onScroll内逻辑
      // <!-- 页面title设置 2023年11月8日新增onScroll="false" 返回字符串“false” 表示前端页面不处理滑动事件； 不配置不返回属性  -->
      return;
    }
  }

  back() {
    this.router.navigateByUrl('home/tab1');
  }

  close() {

    this.router.navigateByUrl('home/tab1');
  }
  /** 收藏 */
  favorite(submit) {
    // 判断是否登录 登录 返回 详情
    const params = {
      id: submit.id,
      content: submit.content,
      sessionId: localStorage.getItem('sessionId')
    };
    console.log('favorite --> submit', params);
    this.http.post('application/submit', params, res => {
      // 请求成功
      if (res.success) {
        // 更新收藏icon UI
        if (this.titleBar.favorite.icon === "unfavorite") {
          this.titleBar.favorite.icon = "favorite";
        } else {
          this.titleBar.favorite.icon = "unfavorite";
        }
        console.log('favorite -->', res.message);
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
        if (res.type === 'page') {
          // to login
          this.pageModalService.openPage({ type: 'page', target: res.target, params: res.params ? res.params : {} });
        }
      }
    });
  }
  // 更多
  moreLine(more) {
    const that = this;
    const buttons: any = [];
    more.data.forEach((element, index) => {
      buttons.push(element.label);
    });

    if (more.style !== undefined) {
      // todo 有style的时候显示popover
      this.presentPopover(null, more.data);
    } else {
      // todo 动作菜单
      ActionSheetService.showActionSheetWithOptions(
        {
          options: buttons,
          maskClosable: true
        },
        buttonIndex => {
          if (buttonIndex > -1) {
            console.log(more.data[buttonIndex]);
            that.selectItem(more.data[buttonIndex]);

          }
        }
      );
    }
  }
  async presentPopover(ev: any, data) {
    const popover = await this.popoverController.create({
      component: PopoverComponent,
      cssClass: 'rightAndTop',
      event: ev,
      mode: 'ios',
      animated: true,
      showBackdrop: false,
      translucent: true,
      componentProps: { tagData: data }
    });
    await popover.present();
    const { role } = await popover.onDidDismiss();
    console.log('onDidDismiss resolved with role', role);
  }
  search(event) {
    if (event && event.keyCode !== 13) {
      return;
    } else {
      this.textButton(this.titleBar.textButton, this.titleBar.searchInput);
    }
  }


  // 确定提交表单用
  textButton(textButton, searchInput?) {
    if (searchInput) {
      // console.log(textButton);
      if (textButton && textButton.link.params.eventName) {
        const listenerName = textButton.link.params.eventName + 'AskForList';
        Object.keys(searchInput.link.params).forEach(key => {
          searchInput.link.params[key] = this.keyword;
        });
        this.eventService.eventEmit.emit(listenerName, searchInput.link);
      }
    } else {
      this.check(textButton);
    }
  }

  check(item) {
    console.log(item.action);
    const keyString: string = item.paramName;
    let keys = keyString ? keyString.split(',') : [];
    // if (!keys) {
    //   return;
    // }
    if (item.action === 'reset') {

      keys.forEach(element => {
        const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);

        if (formGroup) {
          formGroup.reset();
        }
      });

    } else if (item.action === 'submit') {
      // tslint:disable-next-line:no-shadowed-variable
      const keyString: string = item.paramName;
      keys = keyString.split(',');
      let count = 0;
      let formCount = 0;
      keys.forEach(element => {
        const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);
        const messageObj = this.appGlobalService.getFormGroupMessageWithParamName(element);
        const compareArray = this.appGlobalService.getFormCompareWithParamName(element);
        if (formGroup && messageObj) {
          formCount += 1;
          this.valid(formGroup, messageObj, compareArray, params => {
            if (params) {
              item.submit.content[element] = params;
              count += 1;
            } else {
              return;
            }
          });
        }
      });
      // 全部校验通过
      if (count === formCount) {
        if (item.alterMessage && item.alterMessage.length > 0) {
          this.postFormDataTip(item);
        } else {
          this.postFormData(item);
        }
      }

    } else if (item.action === 'link') {
      this.pageModalService.openPage(item.link);
    } else if (item.action === 'question') {
      // alert
      this.question(item, keys);
    } else if (item.action === 'pageModal') {
      this.pageModalService.openPage(item.link);
    } else if (item.action === 'manageShopping') {
      item.label = item.label === '管理' ? '完成' : '管理';
      // TODO: 交互 显示
      // item.link.params.done
      this.eventService.eventEmit.emit('manageShopping', '1');
    } else if (item.action === 'back') {
      this.close();
    } else if (item.action === "share") {
      this.share(item.link);
    }
  }

  // tslint:disable-next-line:ban-types
  valid(formGroup: FormGroup, allLabel, compareArray, callback: Function) {
    if (formGroup.valid) {
      // console.log(this.formGroup.value);
      const params = formGroup.value;
      // tslint:disable-next-line:forin
      for (const prop in params) {
        if (Array.isArray(params[prop])) {
          params[prop] = params[prop].join(',');
        }
        // 删除无效值
        if (prop === '') {
          // delete params[prop];
        }
        if (prop.indexOf('samekey_') > -1) {
          const p = prop.replace('samekey_', '');
          params[p] = params[prop] ? params[prop] : "";
          delete params[prop];
        }
      }
      let compare = true;

      // tslint:disable-next-line:prefer-for-of
      for (let index = 0; index < compareArray.length; index++) {
        const compareItem = compareArray[index];
        if (Number(params[compareItem.minKey]) > Number(params[compareItem.maxKey])) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.lessTip && compareItem.lessTip.length > 0) {
            this.appGlobalService.showToast(compareItem.lessTip, 3000, 'top');
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
          }

          compare = false;
          break;
        } else if (Number(params[compareItem.minKey]) === Number(params[compareItem.maxKey]) && Number(params[compareItem.minKey]) !== 0) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.canEqual) {
            continue;
          } else if (compareItem.equalTip && compareItem.equalTip.length > 0) {
            this.appGlobalService.showToast(compareItem.equalTip, 3000, 'top');
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
          }

          compare = false;
          break;
        }
      }
      if (compare) {
        console.log(params);
        callback(params);
      }
      // this.onReset();
    } else {
      this.getErrors(formGroup, allLabel);
    }
  }

  getErrors(form, allLabel) {
    const errs = [];
    for (const name in form.controls) {
      // eg: controls[name] = phone
      if (form.controls[name].errors) {
        errs.push({ key: [name], err: form.controls[name].errors });
      }
    }
    if (errs.length) {
      const errItem = errs[0];

      const firstErrMsgKey = Object.keys(errItem.err)[0];
      console.log(errItem.key, '校验的字段名');
      const messageObj = allLabel[errItem.key];
      const showMessage = messageObj[firstErrMsgKey];
      this.appGlobalService.showToast(showMessage, 3000, 'top');

    }
  }



  selectItem(item) {
    if (item.action === 'submit') {

      item.submit.sessionId = localStorage.getItem('sessionId');
      console.log('more --> submit', item.submit);
      this.http.post('application/submit', item.submit, res => {
        this.appGlobalService.showToast(res.message, 2000, 'middle');

      });

    } else if (item.action === 'link') {
      const param = {
        pageId: item.link.target,
        params: item.link.params ? item.link.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      this.appGlobalService.goToForward(param);

    } else if (item.action === 'question') {
      // alert
      this.question(item);
    } else if (item.action === 'prompt') {
      // 弹出输入框 alert
      this.inputAlert(item);
    } else if (item.action === "back") {
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
    } else if (item.action === "backToHome") {
      this.router.navigateByUrl('home/tab1');
    } else if (item.action === "back" || item.action === "backNoRefresh") {
      if (item.action === "backNoRefresh") {
        localStorage.removeItem('needRefresh');
      }
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
    } else if (item.action === 'view') {
      const param = {
        viewId: item.link.target,
        params: item.link.params ? item.link.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      this.appGlobalService.goToForward(param);
    } else if (item.action === "share") {
      this.share(item.link);
    }
  }

  // alert
  async question(item, keys?) {
    const alert = await this.alertController.create({

      header: '',
      subHeader: '',
      message: item.question,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('取消');
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          item.submit.sessionId = localStorage.getItem('sessionId');
          console.log('more --> submit', item.submit);
          this.http.post('application/submit', item.submit, res => {
            this.appGlobalService.showToast(res.message, 2000, 'middle');

          });
        }
      }]
    });
    await alert.present();
  }



  async postFormDataTip(item) {
    const that = this;
    const alert = await this.alertController.create({

      header: '',
      subHeader: '',
      message: item.alterMessage,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          that.postFormData(item);
        }
      }]
    });
    await alert.present();

  }
  postFormData(item) {
    item.submit.sessionId = localStorage.getItem('sessionId');
    console.log('check --> submit', item.submit);
    this.http.post('application/submit', item.submit, res => {
      // 请求成功
      if (res.success) {
        this.success(res, item);
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    });
  }
  success(res, item) {
    this.appGlobalService.delFormData();
    if (res.message) {
      this.appGlobalService.showToast(res.message, 2000, 'middle');
    }
    if (item.back) {
      if (Number(item.back) < 0) {
        const back = Math.abs(Number(item.back));
        for (let index = 0; index < back; index++) {
          this.appGlobalService.popTarget();
        }
        this.appGlobalService.goBack(Number(item.back));
        setTimeout(() => {
          if (item.submit && item.submit.content && item.submit.content.tabIndex !== undefined) {
            $('#fixedNavTab' + item.submit.content.tabIndex).click();
          }
        }, 500);
      } else if (Number(item.back) === 0) {
        this.http.reloadCurrentPage();
      } else {
        this.appGlobalService.goBack(Number(item.back));
      }
      if (item.submit.content && item.submit.content.onlyBack !== "true") {
        localStorage.setItem("needRefresh", "true");
      }

    } else if (res.target) {
      this.pageModalService.openPage({
        target: res.target,
        params: res.params ? res.params : {}, type: res.type
      });
    }
    // else {
    //   this.appGlobalService.showToast(res.message, 2000, 'middle');

    // }
  }


  inputAlert(item) {
    const that = this;
    Modal.prompt(
      item.htmlObj.title,
      '',
      [
        {
          text: item.htmlObj.buttonLabel,
          onPress: value =>
            new Promise<void>((resolve, reject) => {
              if (value.length === 0 || that.appGlobalService.isPhone(value)) {
                resolve();
                item.submit.content[item.htmlObj.input.formKey] = value;
                item.submit.sessionId = localStorage.getItem('sessionId');
                console.log('more --> submit', item.submit);
                that.http.post('application/submit', item.submit, res => {
                  if (res.message) {
                    this.appGlobalService.showToast(res.message, 2000, 'middle');
                  }
                });
              } else {
                that.appGlobalService.showToast('请输入正确的号码', 2000, 'top');
              }
            })
        }
      ],
      'default',
      null,
      [item.htmlObj.input.placeholder]
    );
  }
  // 组件销毁方法
  ngOnDestroy(): void {
    if (this.routerSub) {
      // 取消订阅
      this.routerSub.unsubscribe();
    }


  }
  ionViewWillLeave() {
    this.pageModalService.closeAllModal();// 2024.01.05 返回弹窗没有关闭
    if (this.routerSub) {
      // 取消订阅
      this.routerSub.unsubscribe();
    }
  }
  ionViewWillEnter() {
    if (this.eventService.eventEmit.listenerCount('TOTOP') > 0) {
      this.eventService.eventEmit.removeListener('TOTOP');
    }
    this.eventService.eventEmit.on("TOTOP", (obj) => {

      console.log("TOTOP tab1");
      if (this.isScrolling) {
      } else {
        this.appGlobalService.topTop = false;
        this.content.scrollToTop(200);
      }
    });
  }

  // 滑动到顶部
  scrollToTop(event) {
    event.stopPropagation();
    this.content.scrollToTop(1000);
  }


  searchButtonClick(obj, ite?, e?) {

    if (obj.searchType === '200') {

    }
    if (obj.searchType === '300') {
      e.stopPropagation();
      const searchPath = '/navSearch';
      this.router.navigate([searchPath], { queryParams: { obj: JSON.stringify(obj), ite } });
      return;
    }
    if (obj.partLink && obj.partLink.params && obj.partLink.params.key && obj.partLink.params.key.searchButtonCssStyle) {
      if (document.getElementsByTagName('app-nav-one')) {
        const navOneCollection = document.getElementsByTagName('app-nav-one') as HTMLCollection;
        // tslint:disable-next-line:prefer-for-of
        for (let i = 0; i < navOneCollection.length; i++) {
          const el = navOneCollection[i];
          if (!this.hasClass(el, 'ion-page-hidden')) {
            const bottomSearch = el.getElementsByClassName('bottomSearchBox')[0] as HTMLElement;
            const searchDiv = bottomSearch.children[0] as HTMLElement;
            searchDiv.click();
            break;
          }
        }
      }
    } else {
      // search res back to search history
      if (obj.goTo && obj.goTo === "-1") {
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
      } else {
        // to history page
        console.log('to search history');
        localStorage.removeItem('searchParams');
        localStorage.removeItem('invitationArr');
        const searchPath = '/navSearch';
        this.router.navigate([searchPath], { queryParams: { obj: JSON.stringify(obj) } });
      }
    }


  }

  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }

  /**
   * 获取class
   */
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }
  gotoEnterpriseWechat(e) { }
  showTipBox(type) {
    this.appGlobalService.showTipBox(type);
  }
  changeCity(item, event?) {
    if (event !== undefined) {
      event.stopPropagation();
    }
  }

  // 数组btn
  iconButtonClick(item) {
    this.selectItem(item);

  }



}
